package com.srit.source;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 生成模块路径
 * 
 * @author guan
 * 
 */
public class GeneratePackageUtil extends Generate {

	static Logger log = LoggerFactory.getLogger(GeneratePackageUtil.class);

	public GeneratePackageUtil() {
		super();
	}

	public void createModelStructer() {
		for (int i = 0; i < STRUCT.length; i++) {
			new File(modualPath + STRUCT[i]).mkdirs();
		}
	}

	public void copyTemFile() throws IOException {
		List<File> tmpList = this.listFilesInDir(temPath);
		for (int i = 0; i < tmpList.size(); i++) {
			File tem = tmpList.get(i);
			String fileFullName = tem.getName();
			String fileName = fileFullName.substring(0,
					fileFullName.indexOf("."));
			for (int j = 0; j < STRUCT.length; j++) {
				if (STRUCT[j].replace("/", "").indexOf(fileName.toLowerCase()) > 0) {
					if ((STRUCT[j].indexOf("impl") > 0 && fileName
							.toLowerCase().indexOf("impl") > 0)
							|| STRUCT[j].indexOf("impl") < 0
							&& fileName.toLowerCase().indexOf("impl") < 0) {
						copyFileToDir(tem, modualPath + STRUCT[j]);
					}
				}
			}
		}
	}

	/**
	 * 复制模板文件
	 * 
	 * @param file
	 * @param dir
	 * @throws IOException
	 */
	public void copyFileToDir(File file, String dir) throws IOException {
		log.debug("{} is copy!!!", file.getName());
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				file));
		File toFile = new File(dir + "/" + file.getName());
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(toFile));
		byte[] buf = new byte[512];
		int len;
		while ((len = bis.read(buf)) > -1) {
			bos.write(buf, 0, len);
			// bos.write(buf);
		}
		bos.flush();
		if (bis != null) {
			bis.close();
		}
		if (bos != null) {
			bos.close();
		}
	}

	public static void main(String[] args) throws IOException {
		GeneratePackageUtil gp = new GeneratePackageUtil();
		// gp.setModual("cc");
		// gp.createModelStructer();
		// gp.copyTemFile();
		File file = new File(
				"/Users/gjybst/Documents/workspace/ibatis-struts-spring/tem/daoImpl.tem");
		System.out.println(file.exists());
		gp.copyFileToDir(file,
				"/Users/gjybst/Documents/workspace/ibatis-struts-spring/");

		// System.out.println(b);
		// gp.copyTemFile();
	}
}
